<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="设备编码" prop="deviceCode">
        <el-input
          v-model="queryParams.deviceCode"
          placeholder="请输入设备编码"
          clearable
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceTypeId">
        <el-select
          v-model="queryParams.deviceTypeId"
          placeholder="请选择设备类型"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="item in deviceTypeOptions"
            :key="item.typeId"
            :label="item.typeName"
            :value="item.typeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态" prop="deviceStatus">
        <el-select
          v-model="queryParams.deviceStatus"
          placeholder="请选择状态"
          clearable
          style="width: 120px"
        >
          <el-option label="在线" value="online" />
          <el-option label="离线" value="offline" />
          <el-option label="维护中" value="maintenance" />
          <el-option label="故障" value="error" />
        </el-select>
      </el-form-item>
      <el-form-item label="启用状态" prop="isActive">
        <el-select
          v-model="queryParams.isActive"
          placeholder="请选择状态"
          clearable
          style="width: 120px"
        >
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:deviceInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:deviceInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:deviceInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:deviceInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="deviceInfoList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      class="common-table"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="ID" align="center" prop="deviceId" width="80" />
      <el-table-column label="设备编码" align="center" prop="deviceCode" width="120" />
      <el-table-column label="设备名称" align="center" prop="deviceName" width="140" />
      <el-table-column label="设备类型" align="center" prop="deviceTypeId" width="100">
        <template slot-scope="scope">
          <el-tag :type="getDeviceTypeTagType(scope.row.deviceTypeId)" size="small">
            {{ getDeviceTypeName(scope.row.deviceTypeId) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="设备状态" align="center" prop="deviceStatus" width="100">
        <template slot-scope="scope">
          <el-tag :type="getDeviceStatusTagType(scope.row.deviceStatus)" size="small">
            {{ getDeviceStatusLabel(scope.row.deviceStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="信号强度" align="center" prop="signalStrength" width="120">
        <template slot-scope="scope">
          <el-progress 
            :percentage="scope.row.signalStrength || 0" 
            :color="getSignalColor(scope.row.signalStrength)"
            :stroke-width="8"
            :show-text="true"
            :format="() => `${scope.row.signalStrength || 0}%`"
          />
        </template>
      </el-table-column>
      <el-table-column label="IP地址" align="center" prop="ipAddress" width="120" />
      <el-table-column label="安装位置" align="center" prop="installLocation" width="140" show-overflow-tooltip />
      <el-table-column label="负责人" align="center" prop="responsiblePerson" width="80" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" width="110" />
      <el-table-column label="安装日期" align="center" prop="installDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.installDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="isActive" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isActive"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
            :disabled="!checkPermi(['system:deviceInfo:edit'])"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:deviceInfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:deviceInfo:remove']"
            style="color: #F56C6C"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备基础信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="设备编码" prop="deviceCode">
                  <el-input v-model="form.deviceCode" placeholder="请输入设备编码" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备名称" prop="deviceName">
                  <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备类型" prop="deviceTypeId">
                  <el-select v-model="form.deviceTypeId" placeholder="请选择设备类型" style="width: 100%">
                    <el-option
                      v-for="item in deviceTypeOptions"
                      :key="item.typeId"
                      :label="item.typeName"
                      :value="item.typeId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备状态" prop="deviceStatus">
                  <el-select v-model="form.deviceStatus" placeholder="请选择设备状态" style="width: 100%">
                    <el-option label="在线" value="online">
                      <span style="color: #67C23A">在线</span>
                    </el-option>
                    <el-option label="离线" value="offline">
                      <span style="color: #F56C6C">离线</span>
                    </el-option>
                    <el-option label="维护中" value="maintenance">
                      <span style="color: #E6A23C">维护中</span>
                    </el-option>
                    <el-option label="故障" value="error">
                      <span style="color: #F56C6C">故障</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备型号" prop="deviceModel">
                  <el-input v-model="form.deviceModel" placeholder="请输入设备型号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备品牌" prop="deviceBrand">
                  <el-input v-model="form.deviceBrand" placeholder="请输入设备品牌" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="安装位置" prop="installLocation">
                  <el-input v-model="form.installLocation" placeholder="请输入安装位置" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="启用状态" prop="isActive">
                  <el-switch
                    v-model="form.isActive"
                    active-value="1"
                    inactive-value="0"
                    active-text="启用"
                    inactive-text="禁用"
                  >
                  </el-switch>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="网络配置" name="network">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="IP地址" prop="ipAddress">
                  <el-input v-model="form.ipAddress" placeholder="请输入IP地址" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="端口号" prop="port">
                  <el-input-number 
                    v-model="form.port" 
                    :min="1" 
                    :max="65535" 
                    placeholder="端口号" 
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="RTMP流地址" prop="rtmpUrl">
                  <el-input 
                    v-model="form.rtmpUrl" 
                    type="textarea" 
                    placeholder="请输入RTMP流地址"
                    :rows="3"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="信号强度" prop="signalStrength">
                  <el-slider
                    v-model="form.signalStrength"
                    :min="0"
                    :max="100"
                    show-input
                    :show-input-controls="false"
                    style="margin-right: 20px"
                  >
                  </el-slider>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="管理信息" name="management">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="安装日期" prop="installDate">
                  <el-date-picker 
                    v-model="form.installDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择安装日期"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="保修到期" prop="warrantyExpireDate">
                  <el-date-picker 
                    v-model="form.warrantyExpireDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择保修到期日期"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="负责人" prop="responsiblePerson">
                  <el-input v-model="form.responsiblePerson" placeholder="请输入负责人" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="设备参数" prop="deviceParams">
                  <el-input 
                    v-model="form.deviceParams" 
                    type="textarea" 
                    placeholder="请输入设备参数配置（JSON格式）"
                    :rows="4"
                    maxlength="1000"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注信息" prop="remark">
                  <el-input 
                    v-model="form.remark" 
                    type="textarea" 
                    placeholder="请输入备注信息"
                    :rows="3"
                    maxlength="500"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDeviceInfo, getDeviceInfo, delDeviceInfo, addDeviceInfo, updateDeviceInfo } from "@/api/system/deviceInfo";

export default {
  name: "DeviceInfo",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备基础信息表格数据
      deviceInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前活跃标签
      activeTab: "basic",
      // 设备类型选项
      deviceTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceCode: null,
        deviceName: null,
        deviceTypeId: null,
        deviceStatus: null,
        isActive: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceCode: [
          { required: true, message: "设备编码不能为空", trigger: "blur" }
        ],
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        deviceTypeId: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDeviceTypeOptions();
  },
  methods: {
    /** 查询设备基础信息列表 */
    getList() {
      this.loading = true;
      listDeviceInfo(this.queryParams).then(response => {
        this.deviceInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取设备类型选项 */
    getDeviceTypeOptions() {
      // 这里应该调用设备类型API，暂时使用mock数据
      this.deviceTypeOptions = [
        { typeId: 100, typeName: '摄像头' },
        { typeId: 101, typeName: '传感器' },
        { typeId: 102, typeName: '投料机' },
        { typeId: 103, typeName: '增氧机' },
        { typeId: 104, typeName: '水泵' },
        { typeId: 105, typeName: '灯光' }
      ];
    },
    /** 获取设备类型名称 */
    getDeviceTypeName(typeId) {
      const typeMap = {
        100: '摄像头',
        101: '传感器',
        102: '投料机',
        103: '增氧机',
        104: '水泵',
        105: '灯光'
      };
      return typeMap[typeId] || '未知';
    },
    /** 获取设备类型标签类型 */
    getDeviceTypeTagType(typeId) {
      const typeMap = {
        100: 'primary',
        101: 'success',
        102: 'warning',
        103: 'info',
        104: 'danger',
        105: ''
      };
      return typeMap[typeId] || '';
    },
    /** 获取设备状态标签 */
    getDeviceStatusLabel(status) {
      const statusMap = {
        'online': '在线',
        'offline': '离线',
        'maintenance': '维护中',
        'error': '故障'
      };
      return statusMap[status] || status;
    },
    /** 获取设备状态标签类型 */
    getDeviceStatusTagType(status) {
      const statusMap = {
        'online': 'success',
        'offline': 'info',
        'maintenance': 'warning',
        'error': 'danger'
      };
      return statusMap[status] || '';
    },
    /** 获取信号强度颜色 */
    getSignalColor(strength) {
      if (strength >= 80) return '#67C23A';
      if (strength >= 60) return '#E6A23C';
      if (strength >= 40) return '#F56C6C';
      return '#909399';
    },
    /** 处理状态变更 */
    handleStatusChange(row) {
      let text = row.isActive === "1" ? "启用" : "禁用";
      this.$modal.confirm('确认要"' + text + '""' + row.deviceName + '"设备吗？').then(function() {
        return updateDeviceInfo(row);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.isActive = row.isActive === "0" ? "1" : "0";
      });
    },
    /** 权限检查 */
    checkPermi(permissions) {
      return this.$auth.hasPermi(permissions);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        deviceCode: null,
        deviceName: null,
        deviceTypeId: null,
        deviceModel: null,
        deviceBrand: null,
        installLocation: null,
        ipAddress: null,
        port: 8000,
        rtmpUrl: null,
        deviceStatus: "online",
        signalStrength: 80,
        lastOnlineTime: null,
        installDate: null,
        warrantyExpireDate: null,
        responsiblePerson: null,
        contactPhone: null,
        deviceParams: null,
        isActive: "1",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.activeTab = "basic";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceId = row.deviceId || this.ids
      getDeviceInfo(deviceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceId != null) {
            updateDeviceInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeviceInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      const deviceNames = row.deviceName || this.deviceInfoList.filter(item => this.ids.includes(item.deviceId)).map(item => item.deviceName).join('、');
      this.$modal.confirm('是否确认删除设备"' + deviceNames + '"？').then(function() {
        return delDeviceInfo(deviceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/deviceInfo/export', {
        ...this.queryParams
      }, `deviceInfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.common-table {
  margin-top: 10px;
}

.common-table .el-table__header th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 500;
}

.el-tag {
  font-weight: 500;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}

.el-form .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.el-select .el-input__inner {
  cursor: pointer;
}

.el-switch {
  vertical-align: middle;
}

/* 搜索表单优化 */
.el-form--inline .el-form-item {
  margin-bottom: 10px;
}

/* 表格操作按钮间距 */
.el-table .cell .el-button + .el-button {
  margin-left: 5px;
}

/* 标签页优化 */
.el-tabs--border-card .el-tab-pane {
  padding: 20px;
}

.el-tabs--border-card .el-tabs__content {
  background-color: #fff;
}

/* 进度条优化 */
.el-progress--line {
  margin-bottom: 6px;
}

.el-progress__text {
  font-size: 12px !important;
  color: #606266;
}

/* 滑块优化 */
.el-slider {
  margin-bottom: 10px;
}

/* 数字输入框优化 */
.el-input-number {
  width: 100%;
}

/* 弹窗宽度响应式 */
@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
  }
}

/* 表格列头样式优化 */
.el-table th.is-leaf {
  border-bottom: 1px solid #EBEEF5;
}

/* 状态标签样式优化 */
.el-tag.el-tag--success {
  border-color: #67C23A;
}

.el-tag.el-tag--warning {
  border-color: #E6A23C;
}

.el-tag.el-tag--danger {
  border-color: #F56C6C;
}

.el-tag.el-tag--info {
  border-color: #909399;
}
</style>
